package top.pmwly.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.pmwly.common.constant.ReslutEnum;
import top.pmwly.common.reslut.ReslutBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName RestAuthorizationEntryPoint.java
 * @Description 当未登录，或者token失效，访问接口的自定义返回结果
 * @createTime 2021年09月21日 22:30:00
 */
@Component
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String authoriation = request.getHeader("Authoriation");
        //设置编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //输出流
        PrintWriter writer = response.getWriter();
        //结果集返回
        ReslutBean reslut = ReslutBean.FAIL(ReslutEnum.FAIL_AUTHENTICATION);
        //输出
        writer.println( new ObjectMapper().writeValueAsString(reslut));
        //刷新
        writer.flush();
        //关闭流
        writer.close();
    }
}
